package com.feiyuan.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URLEncoder;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 通用类
 */
public class CommonUtils {

    private static final Logger logger = LoggerFactory.getLogger(CommonUtils.class);

    public static String getUtf8(String str) {
        try {
            byte[] bytes = str.getBytes("UTF-8");
            String encode = URLEncoder.encode(new String(bytes), "UTF-8");
            return new String(encode.getBytes("UTF-8"), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 生成六位随机数，用来发送短信验证码
     * @return String
     */
    public static String generateCode() {
        ThreadLocalRandom random = ThreadLocalRandom.current();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            int digit = random.nextInt(10);
            code.append(digit);
        }
        logger.info("this generate code is {}", code);
        return code.toString();
    }

    /**
     * 获取视频的类型
     * @param url 视频地址
     * @return String
     */
    public static String getMovieType(String url) {
        // https://y80s.net/movie/77584
        String[] urls = url.split("/");
        String movieType = urls[urls.length - 2];
        return movieType;
    }

    /**
     * 获取视频在网络上的ID
     * @param url 视频地址
     * @return String
     */
    public static String getMovieWebId(String url) {
        // https://y80s.net/movie/77584
        String[] urls = url.split("/");
        String movieWebId = urls[urls.length - 1];
        return movieWebId;
    }
}
